package com.ledi.guns.modular.ledipay.service.impl;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ledi.guns.common.exception.AppCheckException;
import com.ledi.guns.common.persistence.dao.AgentInfoMapper;
import com.ledi.guns.common.persistence.dao.UserMapper;
import com.ledi.guns.common.persistence.dao.WorkOrderMapper;
import com.ledi.guns.common.persistence.model.TAgentInfo;
import com.ledi.guns.common.persistence.model.User;
import com.ledi.guns.common.persistence.model.WorkOrderInfo;
import com.ledi.guns.core.base.tips.Tip;
import com.ledi.guns.core.redis.KeyValueDAO;
import com.ledi.guns.core.shiro.ShiroKit;
import com.ledi.guns.core.shiro.ShiroUser;
import com.ledi.guns.core.util.HttpUtil;
import com.ledi.guns.core.util.PayUtil;
import com.ledi.guns.core.util.StringUtil;
import com.ledi.guns.core.util.SystemConstans;
import com.ledi.guns.core.util.TimeUtil;
import com.ledi.guns.modular.ledipay.controller.req.H5ApplySchool.AgentResult;
import com.ledi.guns.modular.ledipay.controller.req.H5ApplySchool.H5ApplySchoolInfo;
import com.ledi.guns.modular.ledipay.service.H5ApplySchoolService;

/**
 * 文件名称： com.ledi.guns.modular.ledipay.service.impl.H5ApplySchoolServiceImpl.java<br/>
 * 初始作者： 许芬<br/>
 * 创建日期： 2018年3月1日<br/>
 * 功能说明： 这里用一句话描述这个类的作用--此句话需删除 <br/>
 * =================================================<br/>
 * 修改记录：<br/>
 * 修改作者 日期 修改内容<br/>
 * ================================================<br/>
 * Copyright (橘子股份-幼儿事业部) 2017-2018.All rights reserved.<br/>
 */
@Service
public class H5ApplySchoolServiceImpl implements H5ApplySchoolService {

	protected final static Logger logger = LoggerFactory.getLogger(H5ApplySchoolServiceImpl.class);

	@Autowired
	private AgentInfoMapper AgentInfoMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private KeyValueDAO keyValueDAO;
	@Autowired
	private WorkOrderMapper workOrderMapper;
	@Value("${ledi.sms.url}")
	private String smsUrl;

	@Override
	public AgentResult queryAgentId() {

		AgentResult AgentResult = new AgentResult();
		ShiroUser currentUser = ShiroKit.getUser();
		User user = userMapper.selectById(currentUser.getId());
		TAgentInfo tAgentInfo = AgentInfoMapper.selectById(user.getAgentId());
		AgentResult.setAgentId(tAgentInfo.getId());
		AgentResult.setAgentName(tAgentInfo.getAgentName());

		SortedMap<String, String> finalpackage = new TreeMap<String, String>();
		finalpackage.put("userId", user.getId() + "");
		finalpackage.put("agentId", user.getAgentId() + "");
		finalpackage.put("key", user.getPassword());
		logger.error("--------------签名入参：" + finalpackage.toString());
		String paySign = PayUtil.createSign(finalpackage);
		AgentResult.setSign(paySign);
		AgentResult.setUserId(user.getId());
		return AgentResult;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void applySchoolSms(String mobile) {

		if (!StringUtil.isEmpty(mobile)) {
			boolean isMobile = StringUtil.isMobile(mobile);
			if (!isMobile) {
				throw new AppCheckException("system.user.mobile.format.code", "system.user.mobile.format.message");
			}

			String random = "";
			while (random.length() < 6) {
				random += (int) (Math.random() * 10);
			}

			String heartbeatTime = TimeUtil.addMinutes(TimeUtil.now(), SystemConstans.H5_APPLY_SCHOOL_TIME);

			long time = 0;
			try {
				time = TimeUtil.getTime(heartbeatTime, TimeUtil.SOURCE_1);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			String exitkaptcha = keyValueDAO.get(SystemConstans.H5_APPLY_SCHOOL_KEY.replaceAll("\\{0\\}", mobile));

			keyValueDAO.set(SystemConstans.H5_APPLY_SCHOOL_KEY.replaceAll("\\{0\\}", mobile), random, time);

			HashMap<String, String> param = new HashMap<>();
			param.put("mobile", mobile);
			param.put("templateType", "0");
			param.put("msgKey", "h5.apply.school");
			param.put("params", random + "," + SystemConstans.H5_APPLY_SCHOOL_TIME);
			String response = HttpUtil.post(smsUrl, "utf-8", param);
			Tip tip = JSON.parseObject(response, Tip.class);
			if (tip.getCode() != 200) {
				// 如果验证不通过，设置原来的验证码
				if (StringUtil.isNoneBlank(exitkaptcha)) {
					keyValueDAO.set(SystemConstans.USER_KAPTCHA_KEY.replaceAll("\\{0\\}", mobile), exitkaptcha, time);
				}
				throw new AppCheckException("system.user.mobile.kaptcha.error.code", tip.getMessage());

			}
		} else {
			throw new AppCheckException("system.user.mobile.notBlank.code", "system.user.mobile.notBlank.message");
		}

	}

	@Override
	public void submitWork(H5ApplySchoolInfo h5ApplySchoolInfo) {

		// 数据安全验证
		User user = userMapper.selectById(h5ApplySchoolInfo.getUserId());
		if (user == null || !user.getAgentId().equals(h5ApplySchoolInfo.getAgentId())) {
			throw new AppCheckException("workOrder.addWorkOrderInfoError.code.code",
					"workOrder.addWorkOrderInfoError.code.message");
		}

		SortedMap<String, String> finalpackage = new TreeMap<String, String>();
		finalpackage.put("userId", user.getId() + "");
		finalpackage.put("agentId", user.getAgentId() + "");
		finalpackage.put("key", user.getPassword());
		logger.error("--------------签名入参：" + finalpackage.toString());
		String paySign = PayUtil.createSign(finalpackage);
		if (!StringUtil.equalsIgnoreCase(h5ApplySchoolInfo.getSign(), paySign)) {
			throw new AppCheckException("workOrder.addWorkOrderInfoError.code.code",
					"workOrder.addWorkOrderInfoError.code.message");
		}
		// h5ApplySchoolInfo.setContactTel(StringUtil.removeFourChar(h5ApplySchoolInfo.getContactTel()));
		boolean isMobile = StringUtil.isMobile(h5ApplySchoolInfo.getContactTel());
		if (!isMobile) {
			throw new AppCheckException("system.user.mobile.format.code", "system.user.mobile.format.message");
		}
		h5ApplySchoolInfo.setMailBox(StringUtil.removeFourChar(h5ApplySchoolInfo.getMailBox()));
		boolean isEmail = StringUtil.isEmail(h5ApplySchoolInfo.getMailBox());
		if (!isEmail) {
			throw new AppCheckException("system.mailFormatError.code", "system.mailFormatError.message");
		}

		// 校验验证码
		String exitkaptcha = keyValueDAO
				.get(SystemConstans.H5_APPLY_SCHOOL_KEY.replaceAll("\\{0\\}", h5ApplySchoolInfo.getContactTel()));
		if (!StringUtil.equalsIgnoreCase(h5ApplySchoolInfo.getSmsCode(), exitkaptcha)) {
			throw new AppCheckException("system.user.mobile.kaptcha.code", "system.user.mobile.kaptcha.message");
		}
		String schoolName = StringUtil.removeFourChar(h5ApplySchoolInfo.getSchoolName());
		if (StringUtil.isEmpty(schoolName)) {
			throw new AppCheckException("workOrder.string.error.code", "workOrder.string.error.message",
					new Object[] { "学校名称" });
		}
		h5ApplySchoolInfo.setSchoolName(schoolName);

		String schoolContactPeople = StringUtil.removeFourChar(h5ApplySchoolInfo.getSchoolContactPeople());
		if (StringUtil.isEmpty(schoolContactPeople)) {
			throw new AppCheckException("workOrder.string.error.code", "workOrder.string.error.message",
					new Object[] { "学校联系人名称" });
		}
		h5ApplySchoolInfo.setSchoolContactPeople(schoolContactPeople);
		// 该手机号码是否已经申请工单，如果已经申请，但没处理，直接删除之前的工单，如果是处理中或者已处理，则提示用户不可重复提交
		List<WorkOrderInfo> oldWorkOrderInfoList = workOrderMapper.selectList(new EntityWrapper<WorkOrderInfo>()
				.eq("contact_tel", h5ApplySchoolInfo.getContactTel().trim())
				.eq("is_delete", 0));
		if (oldWorkOrderInfoList != null && oldWorkOrderInfoList.size() > 0) {
			for (WorkOrderInfo oldWorkOrderInfo : oldWorkOrderInfoList) {
				if (oldWorkOrderInfo.getStatus().equals(new Byte((byte) 1))) {
					oldWorkOrderInfo.setIsDelete((byte) 1);
					workOrderMapper.updateById(oldWorkOrderInfo);
				} else {
					throw new AppCheckException("workOrder.addWorkOrderInfoError.existence.code",
							"workOrder.addWorkOrderInfoError.existence.message");
				}
			}
		}

		if (h5ApplySchoolInfo.getIsAlipayPay() == 2) {
			if (StringUtil.isBlank(h5ApplySchoolInfo.getAlipayNumber())) {
				throw new AppCheckException("workOrder.alipayNumber.null.code",
						"workOrder.alipayNumber.null.message");
			}
			String alipayNumber = StringUtil.removeFourChar(h5ApplySchoolInfo.getAlipayNumber());
			if (StringUtil.isEmpty(alipayNumber)) {
				throw new AppCheckException("workOrder.string.error.code", "workOrder.string.error.message",
						new Object[] { "支付宝账号" });
			}
			h5ApplySchoolInfo.setAlipayNumber(alipayNumber);
		}

		if (h5ApplySchoolInfo.getIsAlipayPay() == 2 && h5ApplySchoolInfo.getIsWeixinPay() == 2) {
			if (StringUtil.isBlank(h5ApplySchoolInfo.getPhotoPermitUrl())) {
				throw new AppCheckException("workOrder.photoPermitUrl.null.code",
						"workOrder.photoPermitUrl.null.message");
			}
		} else {
			if (StringUtil.isBlank(h5ApplySchoolInfo.getPhotoPermitUrl())) {
				throw new AppCheckException("workOrder.photoPermitUrl.null.code",
						"workOrder.photoPermitUrl.null.message");
			}
			if (h5ApplySchoolInfo.getSchoolNature() == SystemConstans.TWO && StringUtil.isBlank(h5ApplySchoolInfo.getPhotoOrganizeFrameworkUrl())) {
				throw new AppCheckException("workOrder.photoOrganizeFrameworkUrl.null.code",
						"workOrder.photoOrganizeFrameworkUrl.null.message");
			}
			if (StringUtil.isBlank(h5ApplySchoolInfo.getPhotoOpenAccountUrl())) {
				throw new AppCheckException("workOrder.photoOpenAccountUrl.null.code",
						"workOrder.photoOpenAccountUrl.null.message");
			}
			if (StringUtil.isBlank(h5ApplySchoolInfo.getPhotoIdPositiveUrl())) {
				throw new AppCheckException("workOrder.photoIdPositiveUrl.null.code",
						"workOrder.photoIdPositiveUrl.null.message");
			}
			if (StringUtil.isBlank(h5ApplySchoolInfo.getPhotoIdOppositeUrl())) {
				throw new AppCheckException("workOrder.photoIdOppositeUrl.null.code",
						"workOrder.photoIdOppositeUrl.null.message");
			}
		}
		WorkOrderInfo workOrderInfo = new WorkOrderInfo();
		workOrderInfo.setAgentId(h5ApplySchoolInfo.getAgentId());
		workOrderInfo.setAlipayNumber(h5ApplySchoolInfo.getAlipayNumber());
		workOrderInfo.setContactTel(h5ApplySchoolInfo.getContactTel());
		workOrderInfo.setCreateTime(new Date());
		workOrderInfo.setIsAlipayPay((byte) h5ApplySchoolInfo.getIsAlipayPay());
		workOrderInfo.setIsDelete((byte) 0);
		workOrderInfo.setIsWeixinPay((byte) h5ApplySchoolInfo.getIsWeixinPay());
		workOrderInfo.setMailBox(h5ApplySchoolInfo.getMailBox());
		workOrderInfo.setPhotoIdOppositeUrl(h5ApplySchoolInfo.getPhotoIdOppositeUrl());
		workOrderInfo.setPhotoIdPositiveUrl(h5ApplySchoolInfo.getPhotoIdPositiveUrl());
		workOrderInfo.setPhotoOpenAccountUrl(h5ApplySchoolInfo.getPhotoOpenAccountUrl());
		workOrderInfo.setPhotoOrganizeFrameworkUrl(h5ApplySchoolInfo.getPhotoOrganizeFrameworkUrl());
		workOrderInfo.setPhotoPermitUrl(h5ApplySchoolInfo.getPhotoPermitUrl());
		workOrderInfo.setSchoolContactPeople(h5ApplySchoolInfo.getSchoolContactPeople());
		workOrderInfo.setSchoolName(h5ApplySchoolInfo.getSchoolName());
		workOrderInfo.setStatus((byte) 1);
		workOrderInfo.setVersionNo(0);
		workOrderInfo.setSchoolNature(h5ApplySchoolInfo.getSchoolNature());
		workOrderMapper.insert(workOrderInfo);
	}

}
